package com.dk.controller;

import com.dk.pojo.SslPerson;
import com.dk.pojo.SslRole;
import com.dk.service.SslPersonService;
import com.dk.service.SslRoleService;
import com.dk.shiro.ShiroUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.server.Ssl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("personController")
public class PersonController {


    @DubboReference
    private SslPersonService personService;

    @DubboReference
    private SslRoleService roleService;

    @RequestMapping("list")
    public String list(){
        return "person/list";
    }

    @RequestMapping("findPersonList")
    @ResponseBody
    public List<SslPerson> findPersonList(){
        return personService.findPersonList();
    }
    //跳转到添加页面
    @RequestMapping("toAddPerson")
    public String toAddPerson(Model model){
        List<SslRole> roleList = roleService.findRoleList();
        model.addAttribute("roles", roleList);
        return "person/add";
    }
    //保存用户
    @RequestMapping("savePerson")
    @ResponseBody
    public boolean savePerson(SslPerson pseron,@RequestParam("roleIds[]") Integer[] roleIds){
        String salt = ShiroUtils.generateSalt(6);
        String s = ShiroUtils.encryptPassword("MD5", "1234", salt, 3);
        personService.savePerson(pseron,roleIds,salt,s);
        return true;
    }

    @RequestMapping("toUpdate/{pid}")
    public String toUpdate(@PathVariable("pid") Integer pid, Model model){
        //1、根据id查询用户信息
        SslPerson person = personService.findPersonById(pid);
        //2、查询角色列表
        List<SslRole> roleList = roleService.findRoleList();
        //3、根据当前用户查询用户所拥有的角色id的集合
        List<Integer> roleIds = roleService.findRoleListByPersonId(pid);
        //将结果放入域对象
        model.addAttribute("person", person);
        model.addAttribute("roleList", roleList);
        model.addAttribute("roleIds", roleIds);
        return "person/update";
    }

    //修改用户
    @RequestMapping("updatePerson")
    @ResponseBody
    public boolean updatePerson(SslPerson pseron,@RequestParam("roleIds[]") Integer[] roleIds){
        personService.updatePerson(pseron,roleIds);
        return true;
    }

    @RequestMapping("deletePerson/{pid}")
    @ResponseBody
    public boolean deletePerson(@PathVariable("pid") Integer pid){
        personService.deletePerson(pid);
        return true;
    }
}
